#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
@Author: 李吉凯
@Email: lijk34925@hundsun.com
@Time: 2021/8/2 11:27
@File: queryJira.py
"""

import time
import requests

from src.JIRA.http_opration import DingRebot
from BladeFerm.Lib.Common import logger as mylog
from BladeFerm.utils.SeleniumOperation import GetSessionAndToken


def get_jsession(**params):
    cookies = ''
    obj = GetSessionAndToken(params.get('isClose', True))
    #
    index = 0
    result_login = False
    while index < 4:
        resulut = obj.login_system(**params)
        if resulut:
            result_login = True
            break
        index += 1
        time.sleep(1)
        mylog.warning(f'Retry login ,index : {index}')
    if not result_login:
        obj.close()
        return cookies
    cookies_list = obj.get_cookie()
    if params.get('getToken'):
        tooken = obj.get_token('se.SEConfig.token')
        tookenstr = f'token={tooken};'
        cookies += tookenstr
    obj.close()
    for dic in cookies_list:
        name = dic['name']
        value = dic['value']
        t_info = f'{name}={value}; '
        cookies += t_info
    cookies = cookies.rstrip('; ')
    mylog.info(f'cookies: {cookies}')
    return cookies


def query_issue(jsql, cookies):
    '''
    查询我报告的问题
    :param jsql: 筛选条件，拷贝切换高级后的语句即可
    :param cookies: 登录jira后获取的cookies
    :return:
    '''
    url = 'https://se.hundsun.com/rest/issueNav/1/issueTable'
    header ={
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': cookies,
        '__amdModuleName': 'jira/issue/utils/xsrf-token-header',
        'X-Atlassian-Token': 'no-check',
        'X-Requested-With': 'XMLHttpRequest'
    }
    data = {
        'startIndex': '0',
        'filterId': '-2',
        'jql': jsql,
        'layoutKey': 'list-view'
    }
    res = requests.post(url, data=data, headers=header)
    status = res.status_code
    if status == 200:
        res_info = res.json()
        res_list = res_info['issueTable']['issueKeys']
    else:
        res_list = []
    return res_list


def query_jira_info(dd_info, jira_login, jsql, names_info):
    jrdd = DingRebot(url=dd_info['dd_url'])
    jsesion = get_jsession(**jira_login)
    if not jsesion:
        name = jira_login.get('username')
        phone = names_info.get(name, None)
        tips = f'Jira通知: Jira登录失败，用户{name}的密码未更新！'
        if phone:
            name_list = [phone]
            jrdd.post(tips, name_list=name_list)
        else:
            jrdd.post(tips, isAtAll=True)
        return False
    jrdd = DingRebot(url=dd_info['dd_url'])
    for name, phone in names_info.items():
        jira_sql = jsql.format(name)
        res_list = query_issue(jira_sql, jsesion)
        if len(res_list) > 0:
            info = ','.join(res_list)
            tips = f'JIRA通知:{info}；{dd_info["dd_tip"]}'
            tester = [phone]
            jrdd.post(tips, name_list=tester)
        else:
            mylog.info(f'{name} 没有待验证的缺陷。')


if __name__ == '__main__':
    loginfo = {'username': 'lijk34925', 'password': 'eGluZ0AyMDIx', 'getToken': True, 'isClose': True,
               'jira_url': 'https://hs-cas.hundsun.com/cas/login?service=https%3A%2F%2Fts.hundsun.com%2Fse%2Fj_spring_cas_security_check',
               }
    loginfo2 = {'jira_url': 'https://hs-cas.hundsun.com/cas/login?service=https%3A%2F%2Fts.hundsun.com%2Fse%2Fj_spring_cas_security_check',
            'password': 'bGprODA4N0A=', 'username': 'lijk34925', 'getToken': True, 'isClose': False}
    params = {
        "productId": "20160406",
        "modifyStatus": "5,6"
    }
    # res = get_jsession(**loginfo2)
    # print('res:', res)
    # query_jira_info()